<template>
    <div class="coding-summary-container">
        <div class="page-content">
            <div class="head">
                <h3>修改项详情(非编码)</h3>
                <btn-group :showBtn="showBtn" :code="{exportCode: 100003000004}" @toExport="toExport"/>
            </div>
            <div class="overview">
                <p><span>出院科室：</span>{{overviewData.departmentName}}</p>
                <p><span>病案号：</span>{{overviewData.medicalRecordSign}}</p>
                <p><span>住院次数：</span>{{overviewData.hospitalTime}}</p>
                <p><span>出院日期：</span>{{overviewData.dischargeDate.substring(0, 10)}}</p>
                <p><span>住院医师：</span>{{overviewData.resident}}</p>
                <p><span>编码员：</span>{{overviewData.coder}}</p>
            </div>
            <el-table
                ref="tableData"
                :data="tableData"
                tooltip-effect="light"
                border
                :max-height="tableHeight"
                class="data-table">
                <el-table-column
                    label="序号"
                    type="index"
                    align="center"
                    width="60">
                </el-table-column>
                <el-table-column
                    prop="field"
                    label="填写项目"
                    min-width="160"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="firstContent"
                    min-width="200"
                    label="首次填写值"
                    show-overflow-tooltip>
                </el-table-column>
                <el-table-column
                    prop="lastContent"
                    min-width="200"
                    label="末次填写值"
                    show-overflow-tooltip>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
    import {getZeroTwoNum} from '@/utils/filters'
    import {getModifiedNonCodeList} from '@/api/qc-effect'
    import Pagination from '@/components/Pagination'
    import BtnGroup from '@/components/BtnGroup'
    import FileSaver from 'file-saver'
    import ExcelJS from 'exceljs'

    export default {
        name: 'index',
        data () {
            return {
                // 按钮显示
                showBtn: ['goBack', 'toExport'],
                // 表格数据
                tableData: [],
                // 数据总数
                total: 0,
                // 当前页
                currentPage: 1,
                // 每页数量
                pageSize: 20,
                // 表格高度
                tableHeight: 100,
                // 全局搜索内容，用于翻页等不传参时使用数据
                globalForm: {},
                // 使用储存的数据，不去请求
                useStore: false,
                overviewData: {
                    medicalRecordID: '',
                    departmentName: '',
                    medicalRecordSign: '',
                    hospitalTime: '',
                    dischargeDate: '',
                    resident: '',
                    coder: ''
                },
                // 导出的全部数据
                allexportData: []
            }
        },
        created () {
            // tags判断入口是否从选项卡进入
            this.useStore = this.$route.query.tags === 'tags'
            let height = document.documentElement.clientHeight - 219 - 10 - 78 - 32
            this.tableHeight = height > 107 ? height : 107
            let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
            this.overviewData = query
            this.submitSearch()
        },
        mounted () {
            window.onresize = () => {
                // 其他元素高度60+50+48 10=距离底部边距 78=分页组件高度 5=适应性调整
                let height = document.documentElement.clientHeight - 219 - 10 - 78 - 32
                this.tableHeight = height > 107 ? height : 107
            }
        },
        methods: {
            getZeroTwoNum,
            /**
             * 提交查询
             */
            submitSearch () {
                let params = {
                    medicalRecordID: this.overviewData.medicalRecordID
                }
                this.setGetStore(this.$route.name, params)
                if (this.getSession(this.$route.name, 'getModifiedNonCodeList') && this.useStore) {
                    this.useStore = false
                    let res = this.getSession(this.$route.name, 'getModifiedNonCodeList')
                    if (res.code.toString() === '200') {
                        this.tableData = res.data
                    }
                } else {
                    getModifiedNonCodeList(params).then(res => {
                        this.useStore = false
                        this.setSession(this.$route.name, {getModifiedNonCodeList: res})
                        if (res.code.toString() === '200') {
                            this.tableData = res.data
                        } else {
                            this.$message.error(res.message)
                        }
                    })
                }
            },
            /**
             * 导出编码缺陷列表
             */
            toExport () {
                let params = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                this.$store.dispatch('UpdateLoadingText', '0%')
                this.$store.dispatch('UpdateIsExport', true)
                this.$store.dispatch('UpdateLoading', true)
                params.pageIndex = 1
                params.pageSize = 1000
                this.allexportData = []
                this.sendRequest(params)
            },
            /**
             * 发送请求
             * @param params 请求参数
             */
            sendRequest (params) {
                let allIndex = Math.ceil(this.total / 1000)
                getModifiedNonCodeList(params).then(res => {
                    if (res.code.toString() === '200') {
                        this.$store.dispatch('UpdateLoadingText', parseInt(params.pageIndex / allIndex * 95) + '%')
                        this.allexportData = this.allexportData.concat(res.data)
                        if (params.pageIndex < allIndex) {
                            this.sendRequest({...params, pageIndex: params.pageIndex + 1})
                        } else {
                            this.exportDataList('非编码缺陷汇总明细', this.allexportData)
                        }
                    } else {
                        this.$store.dispatch('UpdateIsExport', false)
                        this.$store.dispatch('UpdateLoading', false)
                        this.$message.error('导出失败')
                    }
                }).catch(() => {
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                    this.$message.error('导出失败')
                })
            },
            /**
             * 导出excel表头
             */
            getHeader () {
                return [{
                    header: '序号', key: 'index', width: 10
                }, {
                    header: '填写项目', key: 'field', width: 32
                }, {
                    header: '首次填写值', key: 'firstContent', width: 24
                }, {
                    header: '末次填写值', key: 'lastContent', width: 24
                }]
            },
            /**
             * 导出列表excel
             */
            exportDataList (name, data) {
                let workbook = new ExcelJS.Workbook()
                workbook.creator = 'lyliang'
                workbook.views = [{
                    x: 0,
                    y: 0,
                    firstSheet: 0,
                    activeTab: 1,
                    visibility: 'visible'
                }]
                let worksheet = workbook.addWorksheet('Sheet1')
                worksheet.columns = this.getHeader()
                for (let i = 0; i < data.length; i++) {
                    data[i].index = i + 1
                    worksheet.addRow(data[i])
                    worksheet.getRow(i + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                    let rate = parseInt((i + 1) / data.length * 0.03 * 100 + 95) + '%'
                    this.$store.dispatch('UpdateLoadingText', rate)
                }
                worksheet.getRow(data.length + 1).alignment = {vertical: 'middle', horizontal: 'center'}
                workbook.xlsx.writeBuffer().then(data => {
                    this.$store.dispatch('UpdateLoadingText', '99%')
                    let blob = new Blob([data], {type: 'EXCEL_TYPE'})
                    FileSaver.saveAs(blob, `${this.parseTime(new Date().getTime())} ${name}.xlsx`)
                    this.$store.dispatch('UpdateLoadingText', '100%')
                    this.$store.dispatch('UpdateIsExport', false)
                    this.$store.dispatch('UpdateLoading', false)
                })
            },
            /**
             * 前往病案明细
             * @param row 行数据
             * @param bool 参数true/false
             */
            toMRList (row, bool) {
                let query = JSON.parse(JSON.stringify(this.$store.state.search.searchForm[this.$route.name]))
                let params = {
                    ...query,
                    orgId: row.org,
                    department: row.departmentCode,
                    departmentName: '',
                    resident: query.department ? row.resident : '',
                    isDefect: bool,
                    pageIndex: 1
                }
                this.$store.dispatch('search/coverSearchFormItem', {
                    pageName: 'CodingListMRListIndex',
                    query: params
                })
                this.$router.push({name: 'CodingListMRListIndex'})
            }
        },
        components: {
            BtnGroup,
            Pagination
        },
        beforeDestroy () {
            window.onresize = null
        }
    }
</script>

<style lang="scss" scoped>
    .coding-summary-container {
        height: calc(100% - 10px);
        .page-content {
            background: #fff;
            padding: 0 10px;
            height: calc(100% - 54px);
        }
        .head {
            display: flex;
            justify-content: space-between;
            align-items: center;
            h3 {
                font-size: 16px;
                color: #000;
                font-weight: 600;
                line-height: 48px;
            }
        }
        .overview {
            display: flex;
            justify-content: flex-start;
            align-items: center;
            margin-bottom: 20px;
            p {
                margin: 0 20px 0 0;
                font-size: 14px;
                color: #333;
                span {
                    font-weight: 600;
                }
            }
        }
    }
</style>
